package com.sheng.project.study.cglib;

import org.junit.Test;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;
import org.springframework.objenesis.instantiator.ObjectInstantiator;

/**
 * @author liusheng
 * @date 2023/06/30
 */
public class CreateObjectTest {

    @Test
    public void test1() {
        // 通过 Objenesis 实现对没有无参构造的类进行无参创建
        Objenesis objenesis = new ObjenesisStd();
        User user = objenesis.newInstance(User.class);
        System.out.println(user);
    }

    @Test
    public void test2() {
        Objenesis objenesis = new ObjenesisStd();
        // 如果需要多次创建时，可以重复利用
        ObjectInstantiator<User> userObjectInstantiator = objenesis.getInstantiatorOf(User.class);
        User user1 = userObjectInstantiator.newInstance();
        System.out.println(user1);
        User user2 = userObjectInstantiator.newInstance();
        System.out.println(user2);
        System.out.println(user1 == user2);
    }

    public static class User {
        private String name;

        public User() {
            // 创建一个无参构造方法，判断 Objenesis 是否会调用(不会调用)
            System.out.println("默认构造函数");
        }

        public User(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}
